package com.gegao.somethinginteresting.utils.fresco.builder;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeController;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.generic.RoundingParams;
import com.facebook.drawee.view.DraweeView;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.request.BasePostprocessor;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.facebook.imagepipeline.request.Postprocessor;
import com.gegao.somethinginteresting.utils.fresco.DrawableUtils;
import com.gegao.somethinginteresting.utils.fresco.FRESCOURITYPE;
import com.gegao.somethinginteresting.utils.fresco.FrescoCacheUtils;
import com.gegao.somethinginteresting.utils.fresco.UriUtils;
import com.gegao.somethinginteresting.utils.fresco.callback.FrescoClearCompleteCallback;

/**
 * 简单Fresco加载构建
 * Created by liuchenghui on 2016/01/05.
 */
public class SimpleLoadFrescoRequestBuilder extends FrescoRequestBuilder {

    protected DraweeView mDraweeView;
    protected Handler mHandler;
    protected Drawable pressDrawable;
    protected Context mContext;
    protected ScalingUtils.ScaleType pressDrawableScaleType;
    protected float mRadius = -1;
    protected float mTopLeft = -1;//左上
    protected float mTopRight = -1;//右上
    protected float mBottomRight = -1;//右下
    protected float mBottomLeft = -1;//左下
    private GenericDraweeHierarchyBuilder mHierarchyBuilder;

    public SimpleLoadFrescoRequestBuilder(DraweeView draweeView) {
        this.mDraweeView = draweeView;
    }


    /**
     * 传入handler让回调在主线程中执行
     *
     * @param handler handler
     */
    public SimpleLoadFrescoRequestBuilder runInMainThread(Handler handler) {
        this.mHandler = handler;
        return this;
    }

    /**
     * @param context                上下文
     * @param pressDrawable          按下图片
     * @param pressDrawableScaleType 缩放类型 (默认为{@link ScalingUtils.ScaleType#CENTER_INSIDE})
     */
    public SimpleLoadFrescoRequestBuilder setPressDrawable(Context context, Drawable pressDrawable, @Nullable ScalingUtils.ScaleType pressDrawableScaleType) {
        if (mContext == null)
            this.mContext = context;
        this.pressDrawable = pressDrawable;
        this.pressDrawableScaleType = pressDrawableScaleType;
        return this;
    }

    /**
     * @param radius 圆角的角度
     */
    public FrescoRequestBuilder setCircleRadius(Context context, float radius) {
        if (mContext == null)
            this.mContext = context;
        this.mRadius = radius;
        return this;
    }

    /**
     * @param radius 圆角的角度
     */
    public FrescoRequestBuilder setRoundAsCircle(Context context, float radius) {
        if (mContext == null)
            this.mContext = context;
        this.mRadius = radius;
        return this;
    }

    /**
     * @param topLeft     左上
     * @param topRight    右上
     * @param bottomRight 右下
     * @param bottomLeft  左下
     */
    public FrescoRequestBuilder setCornersRadii(Context context, float topLeft, float topRight, float bottomRight, float bottomLeft) {
        if (mContext == null)
            this.mContext = context;
        this.mTopLeft = topLeft;
        this.mTopRight = topRight;
        this.mBottomRight = bottomRight;
        this.mBottomLeft = bottomLeft;
        return this;
    }

    /**
     * 开始构建
     */
    @Override
    public void build() {
        if (mDraweeView == null || TextUtils.isEmpty(mUrl))
            return;
        //生成Uri
        Uri uri;
        if (mUrlType == null) {
            mUrlType = FRESCOURITYPE.HTTPURI;
        }
        uri = UriUtils.getUri(mUrl, mUrlType, mPackageName);
        //清除缓存
        if (isClearCache) {
            final Uri finalUri = uri;
            FrescoCacheUtils.clearUriCache(mUrlType, mUrl, mPackageName, new FrescoClearCompleteCallback() {
                @Override
                public void doSomething() {
                    request(finalUri);
                }
            });
        } else {
            request(uri);
        }
    }

    /**
     * 发起加载请求
     */
    private void request(Uri uri) {
        //根据是否添加了回调,是否创建回调对象
        Postprocessor redMeshPostprocessor = null;
        if (mFrescoBitmapCallback != null) {
            redMeshPostprocessor = new BasePostprocessor() {
                @Override
                public String getName() {
                    return mUrl;
                }

                @Override
                public void process(final Bitmap bitmap) {
                    if (mHandler != null && Thread.currentThread() != Looper.getMainLooper().getThread()) {
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                mFrescoBitmapCallback.getBitmap(bitmap);
                            }
                        });
                    } else {
                        mFrescoBitmapCallback.getBitmap(bitmap);
                    }
                }
            };

        }
        //默认设置
        ImageRequestBuilder imageRequestBuilder = ImageRequestBuilder.newBuilderWithSource(uri);
        imageRequestBuilder.setAutoRotateEnabled(true)//许多设备会在JPEG文件的metadata中记录下照片的方向,自动匹配图片方向
                .setLocalThumbnailPreviewsEnabled(true)//如果本地JPEG图，有EXIF的缩略图，image pipeline 会立刻返回一个缩略图。完整的清晰大图，在decode完之后再显示
                .setLowestPermittedRequestLevel(ImageRequest.RequestLevel.FULL_FETCH)//请求经过缓存级别  BITMAP_MEMORY_CACHE，ENCODED_MEMORY_CACHE，DISK_CACHE，FULL_FETCH
                .setProgressiveRenderingEnabled(false);//是否支持 图片渐进式加载
        //添加回调
        if (redMeshPostprocessor != null) {
            imageRequestBuilder.setPostprocessor(redMeshPostprocessor);
        }
        //是否重置尺寸
        if (mWidth > 0 && mHeight > 0) {
            imageRequestBuilder.setResizeOptions(new ResizeOptions(mWidth, mHeight));//图片重置的尺寸
        }
        //开始构建
        ImageRequest request = imageRequestBuilder.build();
        PipelineDraweeController controller = (PipelineDraweeController)
                Fresco.newDraweeControllerBuilder()
                        .setOldController(mDraweeView.getController())
                        .setImageRequest(request)
                        .build();
        GenericDraweeHierarchy hierarchy = null;

        //设置点击的图片
        if (pressDrawable != null) {
            mHierarchyBuilder = new GenericDraweeHierarchyBuilder(mContext.getResources());
            mHierarchyBuilder.setPressedStateOverlay(
                    DrawableUtils.maybeWrapWithScaleType(pressDrawable
                            , pressDrawableScaleType != null ? pressDrawableScaleType : ScalingUtils.ScaleType.CENTER_INSIDE
                            , null));
            mHierarchyBuilder.setActualImageScaleType(ScalingUtils.ScaleType.FIT_CENTER);
        }

        //设置圆角(如果设置了统一的角度,就不能单独设置某个角的角度)
        if (mRadius >= 0 || mTopLeft >= 0 || mTopRight >= 0 || mBottomRight >= 0 || mBottomLeft >= 0) {
            if (mHierarchyBuilder == null)
                mHierarchyBuilder = new GenericDraweeHierarchyBuilder(mContext.getResources());
            RoundingParams roundingParams = null;
            if (mRadius > 0) {
                roundingParams = RoundingParams.fromCornersRadius(mRadius);
//                roundingParams.setBorder(R.color.white, DensityUtils.dp2px(mContext, 2));
//                roundingParams.setOverlayColor(R.color.red);
//                roundingParams.setCornersRadius(mRadius);
            } else {
                roundingParams = RoundingParams.fromCornersRadii(mTopLeft, mTopRight, mBottomRight, mBottomLeft);
            }
            mHierarchyBuilder.setRoundingParams(roundingParams);
        }

        if (pressDrawable != null || mRadius >= 0 || mTopLeft >= 0 || mTopRight >= 0 || mBottomRight >= 0 || mBottomLeft >= 0) {
            hierarchy = mHierarchyBuilder.build();
            mDraweeView.setHierarchy(hierarchy);
        }

        //是否设置占位图
        if (mHolder != null) {
            hierarchy = (GenericDraweeHierarchy) mDraweeView.getHierarchy();
            hierarchy.setPlaceholderImage(mHolder);
        }

        //设置控制器
        mDraweeView.setController(controller);
    }

}
